package com.yl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yl.common.config.YlConfig;
import com.yl.common.core.domain.AjaxResult;
import com.yl.config.ShengWangUrlConfig;
import com.yl.domain.ConferenceApplyDO;
import com.yl.domain.StudentReplyDO;
import com.yl.mapper.ConferenceApplyMapper;
import com.yl.mapper.ConferenceMapper;
import com.yl.mapper.StudentReplyMapper;
import com.yl.service.CommonService;
import com.yl.service.ZhiXingService;
import com.yl.utils.M3u8ToMp3Util;
import com.yl.utils.OssM3U8ToMp3Converter;
import com.yl.utils.speechToText.SpeechFlashRecognizerDemo;
import com.yl.utils.speechToText.SpeechToTextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommonServiceImpl implements CommonService {
    private static final Logger log = LoggerFactory.getLogger(CommonServiceImpl.class);
    @Resource
    StudentReplyMapper studentReplyMapper;
    @Resource
    ConferenceApplyMapper conferenceApplyMapper;
    @Resource
    ZhiXingService zhiXingService;
    @Resource
    ConferenceMapper conferenceMapper;


    /**
     * 定时器 处理会议回答的数据 和生成报告
     *
     * @author : y
     * @date :  2024/7/18 10:30
     **/
    @Override
    public void handleDataAndCreateReport() {
        //  查询今天 没有数据完数据的成员信息
        List<ConferenceApplyDO> listByNotReport = conferenceApplyMapper.findListByNotReport();
        if (listByNotReport != null && listByNotReport.size() != 0) {
            for (ConferenceApplyDO applyDO : listByNotReport) {
                log.info("本次处理的小组成员 name -{}, id - {}, conferenceId - {}, session_id - {}",applyDO.getName(),applyDO.getId(),
                        applyDO.getConferenceId(),applyDO.getSessionId());
                if (applyDO.getSessionId() == null) {
                    continue;
                }
                List<StudentReplyDO> studentReplyList = studentReplyMapper.selectList(Wrappers.<StudentReplyDO>lambdaQuery()
                        .eq(StudentReplyDO::getUserId, applyDO.getId())
                        .eq(StudentReplyDO::getConferenceId, applyDO.getConferenceId()));
                if (studentReplyList != null && studentReplyList.size() != 0) {
                    //处理每条数据信息
                    for (StudentReplyDO studentReplyDO : studentReplyList) {
                        if (StringUtils.isBlank(studentReplyDO.getReplyM3u8VideoUrl())) {
                            log.info("id={},会议id={}，回答的信息replyId={}没有录音文件直接提交职行结果", studentReplyDO.getUserId(), studentReplyDO.getConferenceId(), studentReplyDO.getStudentReplyId());
                            // 提交职行处理好的回答结果
                            submitReply(applyDO.getSessionId(), studentReplyDO);
                            continue;
                        }
                        // m3u8文件转MP3文件
                        String url = studentReplyDO.getReplyM3u8VideoUrl();
                        String mp3Url = YlConfig.getProfile() + studentReplyDO.getStudentReplyId() + ".mp3";
                        System.out.println("存放的MP3文件地址：" + mp3Url);
                        Boolean aBoolean = M3u8ToMp3Util.convertM3U8ToMP3(url, mp3Url);
                        if (!aBoolean) {
                            log.info("m3u8文件生成MP3文件失败");
                            continue;
                        }
                        String newMp3Url = "http://leaderless.zhishudata.com/profile/" + studentReplyDO.getStudentReplyId() + ".mp3";
                        // mp3文件转文字
                        log.info("语音转文字 【入参】=========url={}", newMp3Url);
                        String toText = SpeechToTextUtil.speechToText(newMp3Url);
                        log.info("语音转文字 【生成的文字】==={}", toText);
                        studentReplyDO.setReplyContent(toText);
                        studentReplyDO.setReplyVideoUrl(newMp3Url);
                        studentReplyMapper.updateById(studentReplyDO);
                        // 提交职行处理好的回答结果
                        submitReply(applyDO.getSessionId(), studentReplyDO);
                    }
                }
                applyDO.setUnHandle("1");
                conferenceApplyMapper.updateById(applyDO);
                // 生成报告
                AjaxResult result = zhiXingService.createReport(applyDO.getSessionId());
                if (result == null || !result.get("code").equals(200)) {
                    log.info("创建报告接口 -  失败原因是={}，session_id ={},学生id={}，会议id={},", result.get("msg"), applyDO.getSessionId(),
                            applyDO.getId(),
                            applyDO.getConferenceId());
                    applyDO.setReportStatus("3");
                    conferenceApplyMapper.updateById(applyDO);
                } else {
                    log.info("创建报告接口 - 接口成功 ，session_id：{},学生id={}，会议id={},", applyDO.getSessionId(),
                            applyDO.getId(),
                            applyDO.getConferenceId());
                    applyDO.setReportStatus("1");
                    conferenceApplyMapper.updateById(applyDO);
                }
            }
        }
    }

    public void submitReply(Long sessionId, StudentReplyDO replyDO) {
        JSONObject reply = new JSONObject();
        reply.put("session_id", sessionId);
        reply.put("user_id", replyDO.getUserId());
        reply.put("question_id", replyDO.getQuestionId());
        reply.put("answer_text", replyDO.getReplyContent());
        reply.put("answer_url", replyDO.getReplyVideoUrl());
        reply.put("speak_time", replyDO.getSpeakTime());
        log.info("回答结果提交职行-----入参  - {} ",reply);
        AjaxResult result = zhiXingService.ask_finish(reply.toString());
        if (result == null || !result.get("code").equals(200)) {
            log.info("回答结果提交职行 - 失败原因是={}，回答信息的id={},studentId - {} ", result.get("msg"), replyDO.getStudentReplyId(), replyDO.getUserId());
        } else {
            log.info("回答结果提交职行- 问题成功 id={},学生id - {}", replyDO.getStudentReplyId(), replyDO.getUserId());
        }
    }


    /**
     * 会议结束完成后 前5分钟 每一分钟轮询一次 拉取学生的录音文件
     * 1.m3u8文件转MP3
     * 2.拿到MP3地址转文字
     * 3.填充学生回答结果信息
     * 定时器
     *
     * @author : y
     * @date :  2024/7/14 15:26
     **/
    @Override
    public void batchFillStudentReply() {
        // 查询符合条件的学生回答信息记录  返回回答完毕5分钟之内没有生成文字的结果
        List<StudentReplyDO> list = studentReplyMapper.findListForEnd(8);
        if (list != null && list.size() != 0) {
            for (StudentReplyDO studentReplyDO : list) {
                studentReplyDO.setUnHandle("1");
                // 根据m3u8的地址 去生成MP3文件存到本地
                if (StringUtils.isBlank(studentReplyDO.getReplyM3u8VideoUrl())) {
                    log.info("id={},会议id={}，没有录音文件,数据处理完成", studentReplyDO.getUserId(), studentReplyDO.getConferenceId());
                    studentReplyMapper.updateById(studentReplyDO);
                    continue;
                }
                // m3u8文件转MP3文件
                // String url = "https://zhishubucket-beijing.oss-cn-beijing.aliyuncs.com/" + studentReplyDO.getReplyM3u8VideoUrl();
                String url = studentReplyDO.getReplyM3u8VideoUrl();
                // String substring = studentReplyDO.getReplyM3u8VideoUrl().substring(0, studentReplyDO.getReplyM3u8VideoUrl().lastIndexOf("."));
                String mp3Url = YlConfig.getProfile() + studentReplyDO.getStudentReplyId() + ".mp3";
                Boolean aBoolean = M3u8ToMp3Util.convertM3U8ToMP3(url, mp3Url);
                if (!aBoolean) {
                    log.info("m3u8文件生成MP3文件失败");
                    continue;
                }
                String newMp3Url = "http://leaderless.zhishudata.com/profile/" + studentReplyDO.getStudentReplyId() + ".mp3";
                // mp3文件转文字
                log.info("mp3转文字=========url={}", newMp3Url);
                String toText = SpeechToTextUtil.speechToText(newMp3Url);
                log.info("获取到的文字==={}", toText);
                studentReplyDO.setReplyContent(toText);
                studentReplyDO.setReplyVideoUrl(newMp3Url);
                studentReplyMapper.updateById(studentReplyDO);
            }
        } else {
            log.info("目前没有查询到学生回答完毕的信息======");
        }
    }


    /**
     * 会议结束后第10分钟 把学生的回答结果批量提交职行，并且生成报告
     *
     * @author : y
     * @date :  2024/7/14 15:29
     **/
    @Override
    public void submitZhiXingCreateReport() {
        List<ConferenceApplyDO> listByFinishTime = conferenceApplyMapper.findListByFinishTime();
        if (listByFinishTime != null && listByFinishTime.size() != 0) {
            for (ConferenceApplyDO conferenceApplyDO : listByFinishTime) {
                log.info("本次上传学生名称为====={}", conferenceApplyDO.getName());
                // 查询学生的所有回答结果 该学生本场面试所有的回答次数
                List<StudentReplyDO> list = studentReplyMapper.selectList(Wrappers.<StudentReplyDO>lambdaQuery()
                        .eq(StudentReplyDO::getConferenceId, conferenceApplyDO.getConferenceId())
                        .eq(StudentReplyDO::getUserId, conferenceApplyDO.getId())
                        .isNotNull(StudentReplyDO::getReplyContent)
                        .isNotNull(StudentReplyDO::getReplyVideoUrl)
                );
                if (list != null && list.size() != 0) {
                    for (StudentReplyDO replyDO : list) {
                        JSONObject reply = new JSONObject();
                        reply.put("session_id", conferenceApplyDO.getSessionId());
                        reply.put("user_id", replyDO.getUserId());
                        reply.put("question_id", replyDO.getQuestionId());
                        reply.put("answer_text", replyDO.getReplyContent());
                        reply.put("answer_url", replyDO.getReplyVideoUrl());
                        reply.put("speak_time", replyDO.getSpeakTime());
                        AjaxResult result = zhiXingService.ask_finish(reply.toString());
                        if (result == null || !result.get("code").equals(200)) {
                            log.info("学生回答结果提交问题失败 失败原因是={}，本次回答问题的id={},学生id - {} ", result.get("msg"), replyDO.getStudentReplyId(), replyDO.getUserId());
                        } else {
                            log.info("学生回答结果提交问题成功 id={},学生id - {}", replyDO.getStudentReplyId(), replyDO.getUserId());
                        }
                    }
                }
                // 学生提交所有的回答结果后生成报告
                AjaxResult result = zhiXingService.createReport(conferenceApplyDO.getSessionId());
                if (result == null || !result.get("code").equals(200)) {
                    log.info("学生生成报告接口 失败原因是={}，学生名称：{},学生id={}，会议id={},", result.get("msg"), conferenceApplyDO.getName(),
                            conferenceApplyDO.getId(),
                            conferenceApplyDO.getConferenceId());
                    conferenceApplyDO.setReportStatus("3");
                    conferenceApplyMapper.updateById(conferenceApplyDO);
                } else {
                    log.info("学生生成报告接口成功 ，学生名称：{},学生id={}，会议id={},", conferenceApplyDO.getName(),
                            conferenceApplyDO.getId(),
                            conferenceApplyDO.getConferenceId());
                    conferenceApplyDO.setReportStatus("1");
                    conferenceApplyMapper.updateById(conferenceApplyDO);
                }
            }
        } else {
            log.info("学生提交面试结果目前没有查询数据========");
        }
    }

    /**
     * 每5分钟批量查询报告地址
     *
     * @author : y
     * @date :  2024/7/14 15:29
     **/
    @Override
    public void getReportUrl() {
        List<ConferenceApplyDO> list = conferenceApplyMapper.selectList(Wrappers.<ConferenceApplyDO>lambdaQuery().eq(ConferenceApplyDO::getReportStatus, "1"));
        if (list != null && list.size() != 0) {
            for (ConferenceApplyDO conferenceApplyDO : list) {
                // 获取面试报告
                AjaxResult result = zhiXingService.getReport(conferenceApplyDO.getSessionId(), conferenceApplyDO.getConferenceId());
                log.info("获取面试报告返回参数==========-{}", result);
                if (result == null || !result.get("code").equals(200)) {
                    log.info("获取面试报告失败====失败原因{}", result.get("msg"));
                } else {
                    Map map = JSONObject.parseObject(result.get("data").toString(), Map.class);
                    if (StringUtils.isBlank(map.get("report_url").toString())) {
                        log.info("报告未生成");
                        continue;
                    }
                    conferenceApplyDO.setReportStatus("2");
                    conferenceApplyDO.setReportUrl(map.get("report_url").toString());
                    conferenceApplyMapper.updateById(conferenceApplyDO);
                }
            }
        } else {
            log.info("获取面试报告目前没有数据========");
        }
    }
}
